﻿using MessagePack;
using MessagePack.Formatters;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;


namespace WWDemon.Core
{
    public static class JsonHelper
    {
     
        private static readonly MessagePackSerializerOptions messagePackSerializerOptions = MessagePackSerializerOptions.Standard.WithCompression(MessagePackCompression.Lz4BlockArray);




        public static T ToObject<T>(this string value)
        {
            if (string.IsNullOrWhiteSpace(value)) return default;
            return JsonConvert.DeserializeObject<T>(value);
        }

        public static string ToJson(this object value)
        {
            if (value == null) return string.Empty;


            return JsonConvert.SerializeObject(value);
        }


        public static T ToObjectByte<T>(this byte[] value)
        {
            if (value == null) return default;
            return MessagePackSerializer.Deserialize<T>(value, messagePackSerializerOptions);
        }

        public static byte[] ToJsonByte(this object value, bool isFormat = false)
        {
            if (value == null) return null;

            return MessagePackSerializer.Serialize(value, messagePackSerializerOptions);
        }

        public static JObject ToJObject(this object value)
        {
            if (value == null) return null;
            return JsonConvert.DeserializeObject<JObject>(value.ToJson());
        }

    }


    public class MessagePackDateTimeAttr : IMessagePackFormatter<DateTime>
    {
        public DateTime Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
        {
            return new DateTime(reader.ReadInt64());
        }

        public void Serialize(ref MessagePackWriter writer, DateTime value, MessagePackSerializerOptions options)
        {
            writer.WriteInt64(value.Ticks);
        }
    }
}